package com.wujilee.wujileenetty.netty.aio;

import lombok.Data;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousByteChannel;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future;

/**
 * @author liwuji
 * @date 2024/8/26
 * @desc
 **/
@Data
public class AsyncHandleTimeService  implements Runnable{
    private int port;
    private CountDownLatch countDownLatch;
    private AsynchronousServerSocketChannel  serverSocketChannel;

    public AsyncHandleTimeService(int port) {
        this.port = port;
        AsynchronousServerSocketChannel open = null;
        try {
            open = AsynchronousServerSocketChannel.open();
            open.bind(new InetSocketAddress(8080));
            serverSocketChannel = open;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void run() {
        CountDownLatch countDownLatch1 = new CountDownLatch(1);

        doAccept();
        try {
            countDownLatch1.await();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public void doAccept() {
        serverSocketChannel.accept(this, new CompletionHandler<AsynchronousSocketChannel,AsyncHandleTimeService >(){
            @Override
            public void completed(AsynchronousSocketChannel result, AsyncHandleTimeService attachment) {
                AsynchronousServerSocketChannel serverSocketChannel = attachment.getServerSocketChannel();

                serverSocketChannel.accept(attachment, this);
                ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                 result.read(byteBuffer,byteBuffer,new CompletionHandler<Integer,ByteBuffer>(){
                    @Override
                    public void completed(Integer result, ByteBuffer attachment) {

                    }

                    @Override
                    public void failed(Throwable exc, ByteBuffer attachment) {

                    }
                });

            }

            @Override
            public void failed(Throwable exc, AsyncHandleTimeService attachment) {
                exc.printStackTrace();

            }
        });
    }
}
